package com.soilflow.info.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soilflow.common.annotation.DataScope;
import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.core.domain.TreeSelect;
import com.soilflow.common.core.domain.entity.SysDept;
import com.soilflow.common.domain.LandClassify;
import com.soilflow.common.domain.LandInfoFile;
import com.soilflow.common.domain.dto.LandInfoDto;
import com.soilflow.common.domain.dto.monthstatisticsDto;
import com.soilflow.common.domain.dto.totalstatistics;
import com.soilflow.common.domain.vo.LandInfoVo;

import com.soilflow.common.domain.vo.LandmarkVo;
import com.soilflow.common.domain.vo.TotalByTown;
import com.soilflow.common.domain.vo.callout;
import com.soilflow.common.exception.ServiceException;
import com.soilflow.common.excle.LandInfoExcel;
import com.soilflow.common.excle.im.InfoExcel;
import com.soilflow.common.utils.NoUtils;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.common.utils.StringUtils;
import com.soilflow.common.utils.bean.BeanUtils;
import com.soilflow.info.excelListenner.landInfoListenner;
import com.soilflow.info.service.*;
import com.soilflow.system.service.ISysDeptService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soilflow.common.domain.LandInfo;
import com.soilflow.info.mapper.LandInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.soilflow.common.utils.SecurityUtils.getUserId;

/** 
@author dhp 
@date 2023/4/17 - 16:33
*/
@Service
public class LandInfoServiceImpl extends ServiceImpl<LandInfoMapper, LandInfo> implements LandInfoService{

    @Resource
    private LandInfoFileService landInfoFileService;
    @Autowired
    private ISysDeptService  deptService;
    @Autowired
    private ILandHireService landHireService;
    @Autowired
    private LandContractService landContractService;
    @Autowired
    private LandNoticeService landNoticeService;
    @Autowired
    private LandClassifyService classifyService;
    /* 查询【土地信息】
     *
     * @param id 【土地信息】主键
     * @return 【土地信息】
     */
    @Override
    public LandInfoVo selectLandInfoById(Long id) {
        LandInfoVo landInfoVos = this.baseMapper.selectLandInfoById(id);
        System.out.println("landInfoVos = " + landInfoVos);
        LambdaQueryWrapper<LandClassify> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(LandClassify::getId,landInfoVos.getClassifyId());
        LandClassify one = classifyService.getOne(wrapper);
        System.out.println("one = " + one);
        landInfoVos.setClassifyName(one.getName());
        //转换文件列表为字段
        QueryWrapper<LandInfoFile> infoFileQuery = new QueryWrapper<>();
        //条件
       infoFileQuery.lambda().eq(LandInfoFile::getInfoId, landInfoVos.getId());
        //根据土地id查询文件列表
        List<LandInfoFile> list = landInfoFileService.list(infoFileQuery);
        if (!ObjectUtils.isEmpty(list)&&list.size()>0){
            String file ="";
            //提取出链接
            List<String> files = list.stream().filter(e -> e.getId() != null).map(LandInfoFile::getLink).collect(Collectors.toList());
            //把list转为逗号分割的字符串
            file = StringUtils.join(files, ",");
            landInfoVos.setFile(file);
        }

        return landInfoVos;
    }
    /**
     * 查询【土地信息】列表
     *
     * @param dto 【土地信息】
     * @return 【土地信息】集合
     */
    @Override
    @DataScope(deptAlias = "li")
    public List<LandInfoVo> selectLandInfoList(LandInfoDto dto) {
        List<LandInfoVo> landInfoVos = this.baseMapper.selectLandInfoList(dto);
        // 地图首页设置改土地竞拍状态
        return landInfoVos;
    }

    @Override
    public List<LandInfoVo> selectAllLandList(LandInfoDto dto) {
        List<LandInfoVo> landInfoVos = this.baseMapper.selectAllLandList(dto);
        // 地图首页设置改土地竞拍状态
        return landInfoVos;
    }
    /**
     * 新增【土地信息】
     *
     * @param dto 【土地信息】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertLandInfo(LandInfoDto dto) {

        boolean save =false;
        LandInfo landInfo = new LandInfo();
        BeanUtils.copyProperties(dto,landInfo);
        //级联选择框类型选择
        if (dto.getLandTypeSetList() != null && dto.getLandTypeSetList().size() > 0) {
            List<String> objectTypeSetList = dto.getLandTypeSetList();
            landInfo.setClassifyId(Long.valueOf(objectTypeSetList.get(dto.getLandTypeSetList().size() - 1)));
            landInfo.setLandTypeSet(JSONObject.toJSONString(objectTypeSetList));
        }
        // 土地特色多选框
        if (dto.getLandCharacteristicsList() != null && dto.getLandCharacteristicsList().size() > 0) {
            List<String> objectLandCharacteristicsList = dto.getLandCharacteristicsList();
            landInfo.setLandCharacteristics(JSONObject.toJSONString(objectLandCharacteristicsList));
        }
        save = this.save(landInfo);
        //当存在文件时
      if (!ObjectUtils.isEmpty( dto.getFile())){
          String[] split = dto.getFile().split(",");
          List<LandInfoFile> fileList=new ArrayList<>();
          for (String s : split) {
              //文件
              LandInfoFile landInfoFile = new LandInfoFile();
              landInfoFile.setLink(s);
              landInfoFile.setInfoId(landInfo.getId());
              fileList.add(landInfoFile);
          }
          boolean b = landInfoFileService.saveBatch(fileList);

      }
        return save;
    }
    /**
     * 修改【土地信息】
     *
     * @param dto 【土地信息】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateLandInfo(LandInfoDto dto) {
        boolean save =false;
        LandInfo landInfo = new LandInfo();
        BeanUtils.copyProperties(dto,landInfo);
        //级联选择框类型选择
        if (dto.getLandTypeSetList() != null && dto.getLandTypeSetList().size() > 0) {
            List<String> objectTypeSetList = dto.getLandTypeSetList();
            landInfo.setClassifyId(Long.valueOf(objectTypeSetList.get(dto.getLandTypeSetList().size() - 1)));
            landInfo.setLandTypeSet(JSONObject.toJSONString(objectTypeSetList));
        }
        if (dto.getLandCharacteristicsList() != null && dto.getLandCharacteristicsList().size() > 0) {
            List<String> objectLandCharacteristicsList = dto.getLandCharacteristicsList();
            landInfo.setLandCharacteristics(JSONObject.toJSONString(objectLandCharacteristicsList));
        }
        //当存在文件时
        if (!ObjectUtils.isEmpty( dto.getFile())){
            //删除所有关于土地文件
            Boolean result = landInfoFileService.deleteLandInfoByInfoId(landInfo.getId());

            String[] split = dto.getFile().split(",");
            List<LandInfoFile> fileList=new ArrayList<>();
            for (String s : split) {
                //文件
                LandInfoFile landInfoFile = new LandInfoFile();
                landInfoFile.setLink(s);
                landInfoFile.setInfoId(landInfo.getId());
                fileList.add(landInfoFile);
            }
            boolean b = landInfoFileService.saveBatch(fileList);
        }
        //修改土地信息
        save = this.updateById(landInfo);


        return save;
    }
    /**
     * 批量删除【土地信息】
     *
     * @param ids 需要删除的【土地信息】主键集合
     * @return 结果
     */
    @Override
    public Boolean deleteLandInfoByIds(List<Long> ids) {
        return this.removeByIds(ids);
    }
    /**
     * 查询【竞拍大厅信息】
     *
     * @param dto 【竞拍大厅信息】列表
     * @return 【竞拍大厅信息】
     */
    @Override
    public List<LandInfoVo> selectAuctionLandInfoList(LandInfoDto dto) {
        List<LandInfoVo> landInfoVos = this.baseMapper.selectAuctionLandInfoList(dto);
        List<LandInfoVo> list=new ArrayList<>();
        if (StringUtils.isNotEmpty(dto.getSearchValue())) {
            for (LandInfoVo landInfoVo : landInfoVos) {
                if (landInfoVo != null) {
                    LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SysDept::getDeptName, dto.getSearchValue());
                    SysDept sysDept = deptService.getOne(wrapper);
                    Long deptId = sysDept.getDeptId();
                    if (landInfoVo.getDeptId() == deptId || landInfoVo.getParentId() == deptId) {
                        list.add(landInfoVo);
                    }
                }

            }
            System.out.println("list.size() = " + list.size());
            return list;
        } else {
            return landInfoVos;
        }
    }
    /**
     * 查询【竞拍大厅信息】
     *
     * @param dto 【竞拍大厅信息】列表
     * @return 【竞拍大厅信息】
     */
    @Override
    public List<LandInfoVo> selectRecetionLandInfoList(LandInfoDto dto) {
        return this.baseMapper.selectRecetionLandInfoList(dto);
    }

    /**
     * 查询【竞拍大厅商品信息】
     *
     * @param auctionId 【竞拍大厅商品信息】详情表
     * @return 【竞拍大厅商品信息】
     */
    @Override
    public LandInfoVo selectLandInfoByAuctionId(Long auctionId) {
        LandInfoVo landInfoVo = this.baseMapper.selectLandInfoByAuctionId(auctionId);
        //当不存在竞拍记录时把底价赋值给当前价
        if ( ObjectUtils.isEmpty(landInfoVo.getPriceNow())){
            landInfoVo.setPriceNow(landInfoVo.getReservePrice());
        }
        landInfoVo.setNowTime(new Date());
        return  landInfoVo;
    }

    @Override
    public void exportExcel1(HttpServletResponse response) throws IOException {
        List<LandInfoExcel> landInfos=this.baseMapper.selectExcel();
        for (LandInfoExcel landInfo : landInfos) {
            String plannedUse = landInfo.getPlannedUse();
            String status = landInfo.getStatus();
            if (plannedUse.equals("0")) {
                landInfo.setPlannedUse("加油站");
            } else if (plannedUse.equals("1")) {
                landInfo.setPlannedUse("电影院");
            }else {
                landInfo.setPlannedUse("商场");
            }

            if (status.equals("0")) {
                landInfo.setStatus("预约挂牌");
            } else if (status.equals("1")) {
                landInfo.setStatus("公共竞拍");
            }else {
                landInfo.setStatus("协议转让");
            }
        }
        EasyExcel.write(response.getOutputStream(), LandInfoExcel.class).sheet().doWrite(landInfos);
    }

    @Override
    public void importExcel(MultipartFile file, LandInfoService landInfoService, ISysDeptService deptService, LandClassifyService soilflowClassifyService) throws IOException {
        EasyExcel.read(file.getInputStream(), InfoExcel.class,new landInfoListenner(landInfoService,deptService,soilflowClassifyService)).doReadAll();
    }

    @Override
    public List<monthstatisticsDto> monthstatistics() {
        List<monthstatisticsDto> monthstatisticsDtos = this.baseMapper.monthstatistics();
        return monthstatisticsDtos;
    }

    /**
     * 统计土地总数
     * @return
     */
    @Override
    public int totalLand() {
//        int total = this.baseMapper.totalLand();
        Integer total = this.baseMapper.selectCount(null);
        return total;
    }

    @Override
    public totalstatistics totalstatistics() {
        totalstatistics totalstatistics = new totalstatistics();
        //统计土地总数
        Integer total = this.baseMapper.selectCount(null);
        totalstatistics.setTotal(total);
        //统计今年土地租赁总数
        int thisyear = landHireService.thisyear();
        totalstatistics.setThisyear(thisyear);
        //统计合同总数
        int number = landContractService.number();
        totalstatistics.setNumber(number);
        //统计土地竞拍总数
        int auctions = landNoticeService.number();
        totalstatistics.setAuctions(auctions);
        //统计竞拍类型为公告的数量
        int announcements = landNoticeService.announcements();
        totalstatistics.setAnnouncements(announcements);
        //统计竞拍类型为通知的数量
        int notice = landNoticeService.notice();
        totalstatistics.setNotice(notice);
        return totalstatistics;
    }

    @Override
    public List<LandInfoVo> lists(LandInfoDto landInfo) {
        List<LandInfoVo> landInfoVos = this.baseMapper.lists(landInfo);
        System.out.println("landInfoVo---- = " + landInfoVos);
        return landInfoVos;
    }

    @Override
    public List<LandInfoVo> massifList(LandInfoDto landInfo) {
        List<LandInfoVo> landInfoVos = this.baseMapper.massifList(landInfo);
        return landInfoVos;
    }

    @Override
    public List<LandInfoVo> buildingList(LandInfoDto landInfo) {
        List<LandInfoVo> landInfoVos = this.baseMapper.buildingList(landInfo);
        return landInfoVos;
    }

    @Override
    public List<LandInfoVo> parkList(LandInfoDto landInfo) {
        List<LandInfoVo> landInfoVos = this.baseMapper.parkList(landInfo);
        return landInfoVos;
    }

    @Override
    public List<LandmarkVo> listsJingweidu() {
        List<LandmarkVo> vos=new ArrayList<>();
        List<LandInfo> list = this.list();
        int is=0;
        for (LandInfo landInfo : list) {
            is=is+1;
            LandmarkVo landmarkVo = new LandmarkVo();
            landmarkVo.setId(is);
            if (landInfo.getLatitude()!=null) {
                landmarkVo.setLatitude(Double.parseDouble(landInfo.getLatitude()));
            }
            if (landInfo.getLongitude()!=null){
                landmarkVo.setLongitude(Double.parseDouble(landInfo.getLongitude()));
            }
            landmarkVo.setIconPath("https://staticimg.weikedashi.net/duocaidatonghu/live.png");
            landmarkVo.setWidth("20");
            landmarkVo.setHeight("20");

            callout callout = new callout();
            callout.setContent(landInfo.getLandName());
            callout.setColor("#000");
            callout.setFontSize(10);
            callout.setPadding(5);
            callout.setBgColor("#d2fdff");
            callout.setBorderColor("#466dc8");
            callout.setBorderRadius(5);
            callout.setDisplay("ALWAYS");
            landmarkVo.setCallout(callout);
            vos.add(landmarkVo);
        }
        System.out.println("vos = " + vos);
        return vos;
    }

    @Override
    public LandInfoVo searchLand(String landName) {
        LambdaQueryWrapper<LandInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(LandInfo::getLandName,landName);
        LandInfo one = this.getOne(wrapper);
        LandInfoVo vo = new LandInfoVo();
        BeanUtils.copyProperties(one,vo);
        return vo;
    }

    @Override
    public List<LandmarkVo> parkJingweidu() {
        List<LandmarkVo> vos=new ArrayList<>();
        List<LandInfo> landInfoVos = this.baseMapper.parkJingweidu();
        int is=0;
        for (LandInfo landInfo : landInfoVos) {
            is=is+1;
            LandmarkVo landmarkVo = new LandmarkVo();
            if (landInfo.getLatitude()!=null) {
                landmarkVo.setLatitude(Double.parseDouble(landInfo.getLatitude()));
            }
            if (landInfo.getLongitude()!=null){
                landmarkVo.setLongitude(Double.parseDouble(landInfo.getLongitude()));
            }
            landmarkVo.setId(is);
            landmarkVo.setLatitude(Double.parseDouble(landInfo.getLatitude()));
            landmarkVo.setLongitude(Double.parseDouble(landInfo.getLongitude()));
            landmarkVo.setIconPath("https://staticimg.weikedashi.net/duocaidatonghu/live.png");
            landmarkVo.setWidth("20");
            landmarkVo.setHeight("20");

            callout callout = new callout();
            callout.setContent(landInfo.getLandName());
            callout.setColor("#000");
            callout.setFontSize(10);
            callout.setPadding(5);
            callout.setBgColor("#d2fdff");
            callout.setBorderColor("#466dc8");
            callout.setBorderRadius(5);
            callout.setDisplay("ALWAYS");
            landmarkVo.setCallout(callout);
            vos.add(landmarkVo);
        }
        return vos;
    }

    @Override
    public List<TotalByTown> totalByTown() {
        SysDept sysDept = new SysDept();
        sysDept.setParentId(100L);
        List<SysDept> depts = deptService.selectList(sysDept);
        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(depts);

        List<TotalByTown> totalByTowns = new ArrayList<>();

        for (TreeSelect treeSelect : treeSelects) {
            System.out.println("treeSelect = " + JSONObject.toJSONString(treeSelect));
            TotalByTown totalByTown = new TotalByTown();
            totalByTown.setTownName(treeSelect.getLabel());

            Integer number = baseMapper.totalByTown(treeSelect.getId());
            totalByTown.setNumber(number);

            totalByTowns.add(totalByTown);

        }

        return totalByTowns;
    }

    @Override
    public List<TotalByTown> toVillage() {
        //获取信息
        List<SysDept> depts = deptService.toVillage();
        System.out.println("depts = " + depts);
        List<TotalByTown> totalByTowns = new ArrayList<>();
        for (SysDept dept : depts) {
            //根据土地id统计土地数量
            LambdaQueryWrapper<LandInfo> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(LandInfo::getDeptId,dept.getDeptId());
            int count = this.count(wrapper);
            TotalByTown totalByTown = new TotalByTown();
            totalByTown.setNumber(count);
            totalByTown.setTownName(dept.getDeptName());
            totalByTowns.add(totalByTown);
        }
        return totalByTowns;
    }

}
